package com.yzy.baselibrary.extention

import com.yzy.baselibrary.base.viewmodel.LifecycleViewModel
import com.uber.autodispose.*
import io.reactivex.*

/**
 *description:[LifecycleViewModel]用到的相关扩展.
 *@date 2018/10/15 16:26.
 *@author: YinZeYu.
 */

fun <T> Observable<T>.bindLifecycle(lifecycleViewModel: LifecycleViewModel): ObservableSubscribeProxy<T> =
    bindLifecycle(lifecycleViewModel.lifecycleOwner
        ?: throw throwableWhenLifecycleOwnerIsNull(lifecycleViewModel))

fun <T> Flowable<T>.bindLifecycle(lifecycleViewModel: LifecycleViewModel): FlowableSubscribeProxy<T> =
    bindLifecycle(lifecycleViewModel.lifecycleOwner
        ?: throw throwableWhenLifecycleOwnerIsNull(lifecycleViewModel))

fun <T> Single<T>.bindLifecycle(lifecycleViewModel: LifecycleViewModel): SingleSubscribeProxy<T> =
    bindLifecycle(lifecycleViewModel.lifecycleOwner
        ?: throw throwableWhenLifecycleOwnerIsNull(lifecycleViewModel))

fun <T> Maybe<T>.bindLifecycle(lifecycleViewModel: LifecycleViewModel): MaybeSubscribeProxy<T> =
    bindLifecycle(lifecycleViewModel.lifecycleOwner
        ?: throw throwableWhenLifecycleOwnerIsNull(lifecycleViewModel))

fun Completable.bindLifecycle(lifecycleViewModel: LifecycleViewModel): CompletableSubscribeProxy =
    bindLifecycle(lifecycleViewModel.lifecycleOwner
        ?: throw throwableWhenLifecycleOwnerIsNull(lifecycleViewModel))

private fun throwableWhenLifecycleOwnerIsNull(viewModel: LifecycleViewModel): NullPointerException =
    NullPointerException("$viewModel's lifecycleOwner is null.")
